package com.free.semantic.core;

import com.free.semantic.common.RangeObj;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import okhttp3.*;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class utils {

    public static String getStr(List<RangeObj> sourceObjectList) {
        return sourceObjectList.stream().map(RangeObj::getObjectName).sorted(String::compareTo)
                .collect(Collectors.joining(","));
    }

    public static String getUniqStr(List<RangeObj> sourceObjectList, RangeObj destObj) {
        return String.format("%s_%s", getStr(sourceObjectList), destObj.getObjectName());
    }

    public static String getWeather(String city) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        String cityStr = String.format("q=%s&appid=6b976dbace2a4afdf9545d7dc1271087", convertToPinyin(city));
        MediaType mediaType = MediaType.parse("text/plain");
        Request request = new Request.Builder()
                .url("http://api.openweathermap.org/data/2.5/weather?" + cityStr)
                .method("GET", null)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String convertToPinyin(String chinese) {
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        for (char c : chinese.toCharArray()) {
            try {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                if (pinyinArray != null && pinyinArray.length > 0) {
                    pinyin.append(pinyinArray[0]);
                } else {
                    pinyin.append(c);
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
        }
        return pinyin.toString();
    }

}
